package com.hu.bgp.server;

import java.util.HashSet;
import java.util.Hashtable;
import java.util.Set;
import java.util.UUID;

import com.hu.bgp.framework.ServerFacade;
import com.hu.bgp.framework.ServerFacade.GameState;

public class GameInstanceCollection {

	private Hashtable<String, Hashtable<String, ServerFacade>> index = new Hashtable<String, Hashtable<String, ServerFacade>>();

	private Hashtable<String, ServerFacade> initializingGames = new Hashtable<String, ServerFacade>();
	private Hashtable<String, ServerFacade> waitingGames = new Hashtable<String, ServerFacade>();
	private Hashtable<String, ServerFacade> runningGames = new Hashtable<String, ServerFacade>();

	public GameInstanceCollection() {

	}

	public void put(ServerFacade gameServer, GameState state) {
		Hashtable<String, ServerFacade> collection = getStateCollection(state);

		collection.put(gameServer.getGUID(), gameServer);
		index.put(gameServer.getGUID(), collection);
	}

	public ServerFacade get(String guid) {
		return index.get(guid).get(guid);
	}

	public void remove(String gameServer) {
		index.get(gameServer).remove(gameServer);
		index.remove(gameServer);
	}

	public void changeState(String gameServer, GameState newState) {
		ServerFacade subject = index.get(gameServer).remove(gameServer);
		index.remove(gameServer);
		put(subject, newState);
	}

	public Set<String> getAllinstances() {
		return index.keySet();
	}

	public Set<String> getAllinstances(GameState state) {
		return getStateCollection(state).keySet();
	}

	private Hashtable<String, ServerFacade> getStateCollection(GameState state) {
		switch (state) {
		case initializing:
			return initializingGames;
		case waitingforplayers:
			return waitingGames;
		case running:
			return runningGames;
		default:
			return null;
		}
	}
}
